<?php

/**
 * @author gray.guo
 * 默认bc_db_detection 数据库  使用的AR
 * database => bc_baiaimama
 */
namespace bc\ar;

use yii\db\ActiveRecord;
use yii;

class DActiveRecord extends ActiveRecord
{
	/**
	 * 
	 * @var 自增id
	 */
	public $autoId = 'id';
	
	/**
	 * @var String|array
	 * 字段
	 */
	
	public $columns = '*';
	
	/**
	 * 
	 * @var string
	 * 排序
	 */
	public $sort = null;
	
	
	/**
	 * 设置连接的数据库
	 */
	public static function getDb()
	{
		return Yii::$app->db_detection;
	}
	
	
	/**
	 * 
	 * @param unknown $id
	 */
	public function getRowById($id)
	{
		$row = self::findOne([$this->autoId => $id]);
		if($row)
			return $row->toArray();
		return null;
	}
	
	/**
	 *
	 * @param array $params
	 */
	public function getRow($params = array())
	{
		$row = self::findOne($params);
		if($row)
			return $row->toArray();
		
		return null;
	}
	
	/**
	 *
	 * @param array $data
	 * @return mixed
	 */
	public function add($data)
	{
		if (is_array ( $data ) && ! empty ( $data ))
		{
			foreach ( $data as $key => $value )
			{
				$this->$key = $value;
			}
			$rs = $this->insert ();
			if ($rs === true)
			{
				if ($this->primaryKey ()[0])
					return $this->{$this->primaryKey()[0]};
				else
					return true;
			}
			else
				return 0;
		}
	}
	
	/**
	 * @see \yii\db\ActiveRecord::update()
	 * @param array $data
	 * @param integer $id
	 */
	public function modify($data, $id)
	{
		if (is_array ( $data ) && ! empty ( $data ) && ! is_null ( $id ))
		{
			$row = self::findOne($id);
			foreach ( $data as $key => $value )
			{
				$row->{$key} = $value;
			}
			return $row->save();
		}
	}
	
	/**
	 * 
	 * @param array $params
	 * @param integer $page
	 * @param integer $pageSize
	 */
	public function getList($params, $page = null, $pageSize = null)
	{
		$ar = $this->find ()->select($this->columns)->where($params);
		if ($page && $pageSize)
		{
			$offset = $this->getOffset ( $page, $pageSize );
			$ar->offset($offset)->limit($pageSize);
		}
		if($this->sort == null)
			$ar->orderBy ( $this->autoId . ' DESC' );
		else 
			$ar->orderBy ( $this->sort );
		return $ar->asArray()->all();
	}
	
	/**
	 * 
	 * @param array $condition
	 * @return integer 
	 */
	public function getTotal($condition)
	{
		return $this->find()->where($condition)->count();
	}
	
	
	/**
	 * 
	 * @param integer $page
	 * @param integer $pageSize
	 */
	protected function getOffset($page, $pageSize = 20)
	{
		return ($page - 1) * $pageSize;
	}
	
	
	/**
	 * 通过主键id删除
	 * @param integer $id
	 */
	public function remove($id)
	{
		$row = $this->findOne([$this->autoId => $id]);
		return $row->delete();
	}
	
	/**
	 * 
	 * @param array $condition
	 * @param array $params  'age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']
	 */
	public function removeAll($condition, $params = [])
	{
		if(!empty($condition))
			$this->deleteAll($condition, $params);
	}
}

